package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.reggie.POJO.User;
import com.example.reggie.service.UserService;
import com.example.reggie.utility.R;
import com.example.reggie.utility.ValidateCodeUtils;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    //发生短信验证码
    @PostMapping("/sendMsg")
    public R<String> senMag(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("phone={},code={}",phone,code);
            //发生短信
//            SMSUtils.sendMessage("瑞吉外卖","模板code",phone,code);
            //将验证码和手机号传入session(非常不合适！ 我认为应该存入redis数据库 并设置有效时间)
            session.setAttribute(phone,code);
            return R.success("手机验证码发生成功");
        }
        return R.success("手机验证码发生失败");
    }

    //登录
    @PostMapping("/login")
    public R<User> lgin(@RequestBody Map map, HttpSession session){
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        Object attribute = session.getAttribute(phone);
        if (attribute!=null&&attribute.equals(code)){
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(lambdaQueryWrapper);
            if (user==null){
                //新用户
                user=new User();
                user.setPhone(phone);
                userService.save(user);
            }
            //save有回填id的功能
            session.setAttribute("user",user.getId());
            return  R.success(user);
        }
        return R.error("登录失败");
    }

}
